<script>

import {
  builderOrderPlan,
  getCategoryOptions,
  keyWordUsageRecordList,
  removeKeyWordUsage
} from "@/views/manage/keyWord/api";
import { formatPercentage, isNull } from "@/utils/service";
import FeatureTemplate from "@/views/manage/keyWord/component/featureTemplate.vue";
import CopyKeyWordBtn from "@/views/manage/keyWord/component/copyKeyWordBtn.vue";
import { getOptions as getGroupOptions, groupIdToGroupName } from "@/views/manage/keyWord/component/groupApi";
import KeyWordGroup from "@/views/manage/keyWord/component/keyWordGroup.vue";
export default {
  name: "orderPlanGenerate",
  components: { KeyWordGroup, CopyKeyWordBtn, FeatureTemplate },
  computed: {
    pageData(){
      const start = (this.page.current - 1) * this.page.size;
      const end = start + this.page.size;
      return this.keyWordList.slice(start, end);
    }
  },
  mounted(){
    let _ = this
    getCategoryOptions(this,"categoryOptions")
    getGroupOptions(_,null,r=> {
      _.allGroupOptions = r
      _.groupOptions = r
    },f=>{})
  },
  data(){
    return {
      /* 选中的品类*/
      selectCategory: '',
      /*品类选项*/
      categoryOptions: [],
      /* 所有分组选项*/
      allGroupOptions: [],
      /* 分组选项*/
      groupOptions: [],
      /* 选中的分组id */
      groupSelectId: [],
      /* 选项加载*/
      groupSelectLoading: true,
      /*关键词列表*/
      keyWordList: [],
      /*分页对象*/
      page: {
        selectRow: [],
        loading: false,
        size: 10,
        current: 1,
      },
      /* 补单编辑抽屉 */
      fillOrderShow: false,
      taskParams: {
        /* 生成补单周期天数 */
        builderOrderDay: 7,
        /* 用于生成补单计划的关键词 从 selectRow 即,表格选中的关键词导入 */
        fillOrderKeyWord: [],
      }
    }
  },
  methods: {
    isNull,
    getKeyWordUsageRecordList() {
      let _t = this;
      keyWordUsageRecordList(this,this.selectCategory,this.groupSelectId
        ,"IS_GENERATE_ORDER_PLAN", res => {
        _t.keyWordList = res;
      });
    },
    selectGroupChange(v){
      if (isNull(v)) {
        this.groupSelectId = null;
      }
      this.getKeyWordUsageRecordList();
    },
    selectCategoryChange(v){
      let _t = this;
      if(isNull(v)){
        return;
      }
      this.getKeyWordUsageRecordList()
    },
    tableSelectChange(v){
      this.page.selectRow = v
    },
    tableSortChange(column, prop, order){
      if (!isNull(column.order)) {
        if (column.order.startsWith("asc")) {
          this.keyWordList.sort((a, b) => a[column.prop] - b[column.prop]);
        } else {
          this.keyWordList.sort((a, b) => b[column.prop] - a[column.prop]);
        }
      } else {
        this.keyWordList.sort((a, b) => b["searchPeopleNum"] - a["searchPeopleNum"]);
      }
    },
    delTableRow(delRows){
      let _ = this;
      if (delRows.length === 0) {
        this.$message.warning("没有选择删除目标");
        return;
      }
      _.page.loading = true;
      removeKeyWordUsage(this, JSON.stringify(delRows.map(i => i.id)), "IS_GENERATE_ORDER_PLAN",
        data => {
          _.$message.success("提交成功");
          _.getKeyWordUsageRecordList(_.selectCategory);
        }, res => {
          _.page.loading = false;
        });
    },
    pageSizeChange(v){
      this.page.size = v
    },
    pageCurrentChange(v){
      this.page.current = v
    },
    openFillOrder(){
      this.fillOrderShow = true;
    },
    loadSelectKeyToFillOrder(){
      let _ = this
      if (this.page.selectRow.length === 0){
        this.$message.warning("请先选中关键词")
        return;
      }
      // 根据关键词名称去重
      let appendKey = this.page.selectRow.filter(i => {
        return !_.taskParams.fillOrderKeyWord.some(j => j.name === i.name)
      })
      _.taskParams.fillOrderKeyWord.push(...appendKey)
    },
    builderOrderPlan() {
      if (this.taskParams.fillOrderKeyWord.length === 0){
        this.$message.warning("您没有载入任何关键词")
        return
      }
      builderOrderPlan(this, this.taskParams.fillOrderKeyWord, this.taskParams.builderOrderDay)
    },
    defTemplate() {
      this.taskParams.builderOrderDay = 7
      this.taskParams.fillOrderKeyWord = []
    },
    loadTemplate(params){
      this.taskParams = params
    },
    checkParam(){
      if (this.taskParams.fillOrderKeyWord.length === 0){
        this.$message.warning("没有载入任何关键词")
        return false
      }
      return true;
    },
    /** 将表格值转为百分比*/
    valueToPercentage(row, column, cellValue, index) {
      return formatPercentage(cellValue);
    },
    /** 表格值保留两位小数*/
    percentageWithFixedDigits2(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(2) : "-";
    },
    /** 表格值保留三位小数*/
    percentageWithFixedDigits4(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(4) : "-";
    },
    groupIdFormatName(row, column, cellValue, index){
      return groupIdToGroupName(cellValue,this.allGroupOptions)
    },
    groupSelectVisibleChange(v){
      let _ = this;
      _.groupSelectLoading = true;
      if (v){
        getGroupOptions(_,null,r=> {
          _.allGroupOptions = r;
          _.groupOptions = r.filter(i => i.categoryName === _.selectCategory || i.id === 0);
        },f => {
          _.groupSelectLoading = false
        })
      }
    }
  },
}
</script>

<template>
  <div style="margin: 10px 0">
    <!-- 头部内容  -->
    <div class="header">
      <div>
        <el-select
          @change="selectCategoryChange"
          style="width: 230px"
          size="mini" v-model="selectCategory" clearable filterable placeholder="请筛选品类">
          <el-option
            v-for="item in categoryOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-select
          v-if="!isNull(selectCategory)"
          @change="selectGroupChange"
          @visible-change="groupSelectVisibleChange"
          :loading="groupSelectLoading"
          loading-text="加载中...."
          style="width: 230px;margin-left: 5px;"
          size="mini" v-model="groupSelectId" clearable filterable placeholder="请选择分组">
          <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>

      <div style="margin-top: 5px">

        <key-word-group
          @updateTable="getKeyWordUsageRecordList"
          :select-row=page.selectRow
          :group-options=groupOptions
          :show-edit="true"
          style="margin-right: 5px;"
        >
        </key-word-group>

        <el-popconfirm
          style="margin-right: 5px;"
          confirm-button-text='是的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="确定要移除选中项吗？"
          @confirm="delTableRow(page.selectRow)"
        >
          <el-button
            slot="reference"
            v-show="keyWordList.length > 0"
            :disabled="page.selectRow.length === 0"
            type="danger"
            size="mini"
          >
            移除选中项
          </el-button>
        </el-popconfirm>

        <copy-key-word-btn
          style="margin-right: 5px;"
          :select-row="page.selectRow"
          :show="keyWordList.length > 0"
        >
        </copy-key-word-btn>

        <el-button
          slot="reference"
          v-loading="page.loading"
          v-show="keyWordList.length > 0"
          type="success"
          size="mini"
          @click="openFillOrder"
        >
          生成补单周期面板
        </el-button>

      </div>

    </div>

    <div class="main">
      <div>
        <el-table
          @selection-change="tableSelectChange"
          v-loading="page.loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          style="width: 100%"
          height="73vh"
          :row-style="{height:'20px'}"
          :cell-style="{padding:'0px'}"
          border
          :data="pageData"
          @sort-change="tableSortChange"
        >
          <el-table-column fixed="left" align="center" type="selection" width="40"/>
          <el-table-column fixed="left" align="center" :show-overflow-tooltip=true prop="name" label="关键词" width="200"/>
          <el-table-column fixed="left" align="center" :show-overflow-tooltip=true prop="groupId" label="组名"
                           :formatter="groupIdFormatName"
                           width="200">
          </el-table-column>
          <el-table-column align="center" prop="adId" label="操作人编号" width="100"/>
          <el-table-column prop="searchPeopleNum" sortable label="搜索人数" align="center" width="110"/>
          <el-table-column prop="searchCount" sortable label="搜索次数" align="center" width="110"/>
          <el-table-column prop="clickRate" sortable label="点击率" width="100" align="center" :formatter="valueToPercentage"/>
          <el-table-column prop="clickPeopleNum" sortable label="点击人数" align="center" width="110"/>
          <el-table-column prop="clickCount" sortable label="点击次数" align="center" width="110"/>
          <el-table-column prop="transactionAmount" sortable label="交易金额" align="center" width="110"
                           :formatter="percentageWithFixedDigits2"/>
          <el-table-column prop="paymentConversionRate" sortable label="ROI" align="center" width="110"
                           :formatter="valueToPercentage"/>
          <el-table-column prop="onlineGoodsNum" align="center" sortable label="在线商品数" width="120" />
          <el-table-column prop="mallClickRate" align="center" sortable label="商城点击比例" width="130"
                           :formatter="valueToPercentage" />
          <el-table-column prop="ztcReferencePrice" align="center" sortable label="直通车参考价" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="paymentPeopleNum" align="center" sortable label="支付人数" width="110" />
          <el-table-column prop="unitPrice" sortable align="center" label="客单价" width="100"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="searchUsersPerGoods" align="center" sortable label="搜索人数/在线商品数" width="180"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="transactionAmountPerGoods" align="center" sortable label="交易金额/在线商品数"
                           width="180"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="visitorAverageValue" align="center" sortable label="访客平均价值" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="goodsAverageValue" align="center" sortable label="商品平均价值" width="130"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="visitorCompetitionIndex" align="center" label="商品访客竞争度" width="120"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="highQualityValueWords" align="center" sortable label="优质价值词" width="120" />
          <el-table-column prop="competitionDegree" align="center" sortable label="竞争度" width="120"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="estimatedConversionQuantity" align="center" sortable label="预估转化件数" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="averageTransactionIndex" align="center" sortable label="平均交易指数" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column align="center" prop="createTime" sortable label="创建时间" width="200"/>
          <el-table-column align="center" prop="updateTime" sortable label="修改时间" width="200"/>
          <el-table-column fixed="right" align="center" prop="updateTime" label="操作" width="80">
            <template  slot-scope="{row}">
              <div style="margin:5px">
                <el-button size="mini" type="danger" @click="delTableRow([row])">移除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="footer">
      <div>
        <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageCurrentChange"
          :current-page="page.current"
          :page-sizes="[10,50,100, 200, 300,500,1000]"
          :page-size=page.size
          layout="total, sizes, prev, pager, next, jumper"
          :total=keyWordList.length>
        </el-pagination>
      </div>
      <div>
        <span class="label">选中数据量 : </span>
        <span style="font-weight: bold">{{page.selectRow.length}}</span>
      </div>
    </div>

    <el-drawer
      size="35%"
      :visible.sync="fillOrderShow"
      direction="rtl"
      title="补单周期面板"
    >
      <div style="margin: 0 10px;height: 86.5vh">
        <FeatureTemplate
          type="GENERATE_ORDER_PLAN"
          :task-params="taskParams"
          :def-template="defTemplate"
          :load-template="loadTemplate"
          :check-param="checkParam"
        >
        </FeatureTemplate>
        <div style="margin: 10px 0">
          <span class="label">分布订单天数 : </span>
          <el-input-number size="mini" v-model="taskParams.builderOrderDay" :min=1 :max=90></el-input-number>
        </div>
        <div style="margin: 10px 0">
          <el-button size="mini" @click="loadSelectKeyToFillOrder">载入选中的关键词</el-button>
          <el-button size="mini" @click="taskParams.fillOrderKeyWord = []">清空所有关键词</el-button>
        </div>
        <el-card shadow="always" style="height: 70vh;overflow-y:scroll">
          <div>
            <el-tag
              style="margin:2px 4px"
              size="small"
              v-for="(tag,index) in taskParams.fillOrderKeyWord"
              :key="tag.id"
              closable
              @close="taskParams.fillOrderKeyWord.splice(index,1)"
            >
              {{tag.name}}
            </el-tag>
          </div>
        </el-card>
      </div>
      <div style="text-align: center">
        <el-button
          style="width: 98%"
          type="success"
          @click="builderOrderPlan"
          :disabled="taskParams.fillOrderKeyWord.length === 0"
        >
          生成补单周期
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.header{

}
.main{
  margin: 10px 0;
}
.footer{
  display: flex;
  justify-content: space-between;
}
.label {
  color: #57606f;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 0.05em;
}
</style>